package com.ndphu.comic.gui.fragment.book;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.ndphu.comic.R;

public class BitmapPageFragment extends Fragment {

	private static final int MAX_SIZE = 4096;
	private Bitmap content;
	private LinearLayout mainContainer;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_book_page, container, false);
		mainContainer = (LinearLayout) view.findViewById(R.id.container);
		mainContainer.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				System.out.println("Touched");
				return false;
			}
		});
		if (content != null) {
			renderContent();
		}
		return view;
	}

	public Bitmap getContent() {
		return content;
	}

	public void setContent(Bitmap content) {
		this.content = content;
		if (mainContainer != null) {
			renderContent();
		}
	}

	private void renderContent() {
		if (this == null || this.getActivity() == null) {
			return;
		}
		int max = content.getWidth() > content.getHeight() ? content.getWidth() : content.getHeight();
		if (max < 4096) {
			ImageView iv = new ImageView(this.getActivity());
			iv.setImageBitmap(content);
			mainContainer.addView(iv);
		} else {
			if (max == content.getHeight()) {
				int time = max / MAX_SIZE;
				int i = 0;
				for (; i < time; ++i) {
					Bitmap subBitmap = Bitmap.createBitmap(content, 0, i * MAX_SIZE, content.getWidth(), MAX_SIZE);
					ImageView iv = new ImageView(this.getActivity());
					iv.setImageBitmap(subBitmap);
					mainContainer.addView(iv);
				}
				Bitmap subBitmap = Bitmap.createBitmap(content, 0, time * MAX_SIZE, content.getWidth(), max % MAX_SIZE);
				ImageView iv = new ImageView(this.getActivity());
				iv.setImageBitmap(subBitmap);
				mainContainer.addView(iv);
			}
		}
	}
}
